package com.example.outdoor;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import org.json.JSONObject;

import android.app.ListActivity;
import android.app.PendingIntent.OnFinished;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import android.text.Layout;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class FileChooser extends ListActivity {
	SQLiteDatabase db1 = null;
	private static String DBNAME = "OutdoorAppDB.db";
	private File currentDir;
	private FileArrayAdapter adapter;
	ProgressBar pr;
	ListView lv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.filechooser);
		// lv = (ListView) findViewById(R.id.ListView01);

		currentDir = new File("sdcard/");
		fill(currentDir);
//		 onFileClick();
	}

	private void fill(File f) {
		File[] dirs = f.listFiles();
		this.setTitle("Current Dir: " + f.getName());
		List<Option> dir = new ArrayList<Option>();
		List<Option> fls = new ArrayList<Option>();
		try {
			for (File ff : dirs) {
				if (ff.isDirectory())
					dir.add(new Option(ff.getName(), "Folder", ff
							.getAbsolutePath()));
				else {
					fls.add(new Option(ff.getName(), "File Size: "
							+ ff.length(), ff.getAbsolutePath()));
				}
			}
		} catch (Exception e) {

		}
		Collections.sort(dir);
		Collections.sort(fls);
		dir.addAll(fls);
		if (!f.getName().equalsIgnoreCase("sdcard"))
			dir.add(0, new Option("..", "Parent Directory", f.getParent()));
		adapter = new FileArrayAdapter(FileChooser.this, R.layout.filechooser,
				dir);
		// lv.setAdapter(adapter);
		/*
		 * pr = (ProgressBar) findViewById(R.id.progressBar1);
		 * pr.setVisibility(View.INVISIBLE);
		 */
		this.setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);

		// pr.setVisibility(View.VISIBLE);
		Option o = adapter.getItem(position);
		if (o.getData().equalsIgnoreCase("folder")
				|| o.getData().equalsIgnoreCase("parent directory")) {
			currentDir = new File(o.getPath());
			fill(currentDir);
		} else {
			onFileClick(o);
			// pr.setVisibility(View.GONE);
		}
	}

	private void onFileClick(Option o) {
		try {
			// Toast.makeText(this, "File Clicked: "+o.getPath(), ToORT).show();
			// pr.setVisibility(View.VISIBLE);
			db1 = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

			// Create Table
			this.db1.execSQL("CREATE TABLE IF NOT EXISTS tblBillboard(ID INTEGER PRIMARY KEY , Avenue INTEGER,Date NNVARCHAR,Starttime NVARCHAR,Endtime NVARCHAR,Size NVARCHAR,Carrier NVARCHAR,CarrierDescription NVARCHAR,Quality NVARCHAR,RealCost NVARCHAR,LatandLong NVARCHAR,Numberofads NVARCHAR,Totaladsinthatlocation NVARCHAR,typeofads NVARCHAR,Visibilitycode NVARCHAR,Visibilitydescription NVARCHAR,Verificationdate NVARCHAR,Verificationdescription NVARCHAR,Versiocode NVARCHAR,Versiondescription NVARCHAR,Productcode NVARCHAR,Constant NVARCHAR,CategoryCode NVARCHAR,Categorydescription NVARCHAR,Subsectorcode NVARCHAR,Subsectordescription NVARCHAR,Sectorcode NVARCHAR,Sectordescription NVARCHAR,Betweenavenue NVARCHAR,Brandcode NVARCHAR,Branddescription NVARCHAR,Announcercode NVARCHAR,Announcerdescription NVARCHAR,Imagecode NVARCHAR,Agencycode NVARCHAR,Agencyname NVARCHAR,Condition NVARCHAR,Obstruction NVARCHAR); ");
			//db1.execSQL("CREATE TABLE IF NOT EXISTS tblBillboard(ID INTEGER PRIMARY KEY , Avenue INTEGER,Date NNVARCHAR,Starttime NVARCHAR,Endtime NVARCHAR,Size NVARCHAR,Carrier NVARCHAR,CarrierDescription NVARCHAR,Quality NVARCHAR,RealCost NVARCHAR,LatandLong NVARCHAR,Numberofads NVARCHAR,Totaladsinthatlocation NVARCHAR,typeofads NVARCHAR,"
				//	+ "Visibilitycode NVARCHAR,Visibilitydescription NVARCHAR,Verificationdate NVARCHAR,Verificationdescription NVARCHAR,Versiocode NVARCHAR,Versiondescription NVARCHAR,Productcode NVARCHAR,Constant NVARCHAR,CategoryCode NVARCHAR,Categorydescription NVARCHAR,Subsectorcode NVARCHAR,Subsectordescription NVARCHAR,Sectorcode NVARCHAR,"
					//+ "Sectordescription NVARCHAR,Betweenavenue NVARCHAR,Brandcode NVARCHAR,Branddescription NVARCHAR,Announcercode NVARCHAR,Announcerdescription NVARCHAR,Imagecode NVARCHAR,Agencycode NVARCHAR,Agencyname NVARCHAR); ");
			db1.execSQL("create table IF NOT EXISTS tblOBSTRUCTION (id INTEGER PRIMARY KEY,Obstruction  TEXT);");
			db1.execSQL("create table IF NOT EXISTS tblCondition (ID INTEGER PRIMARY KEY,Condition  TEXT);");
			
			this.db1.execSQL("create table IF NOT EXISTS tblANTERIOR (ID INTEGER PRIMARY KEY,Avenue  VARCHAR,BillboardID VARCHAR);");
		      this.db1.execSQL("CREATE TABLE IF NOT EXISTS tblBillboardhistory(ID INTEGER PRIMARY KEY ,OriginalID INTEGER, Avenue INTEGER,Date NNVARCHAR,Starttime NVARCHAR,Endtime NVARCHAR,Size NVARCHAR,Carrier NVARCHAR,CarrierDescription NVARCHAR,Quality NVARCHAR,RealCost NVARCHAR,LatandLong NVARCHAR,Numberofads NVARCHAR,Totaladsinthatlocation NVARCHAR,typeofads NVARCHAR,Visibilitycode NVARCHAR,Visibilitydescription NVARCHAR,Verificationdate NVARCHAR,Verificationdescription NVARCHAR,Versiocode NVARCHAR,Versiondescription NVARCHAR,Productcode NVARCHAR,Constant NVARCHAR,CategoryCode NVARCHAR,Categorydescription NVARCHAR,Subsectorcode NVARCHAR,Subsectordescription NVARCHAR,Sectorcode NVARCHAR,Sectordescription NVARCHAR,Betweenavenue NVARCHAR,Brandcode NVARCHAR,Branddescription NVARCHAR,Announcercode NVARCHAR,Announcerdescription NVARCHAR,Imagecode NVARCHAR,Agencycode NVARCHAR,Agencyname NVARCHAR,Condition NVARCHAR,Obstruction NVARCHAR); ");
		      this.db1.execSQL("create table IF NOT EXISTS tblNewProduct (ID INTEGER PRIMARY KEY,Avenue  TEXT,Product VARCHAR,Version VARCHAR);");
		      db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('EXCELENTE');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('BUENA');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('REGULAR');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('DETERIORADA');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('GRAFITI');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('MALA');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('MALA ORIENTACION');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('SUCIO');");
				db1.execSQL("INSERT INTO tblCondition  (Condition)  VALUES ('NINGUNA');");

				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('ANGULO');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('ARBOLES');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('EDIFICIO');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('GRAFITIS');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('OTRO AVISO');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('PARADA');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('POSTE DE LUZ');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('RAMA');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('SEMAFORO');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('TENDIDO ELECTRICO');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('OTROS');");
				db1.execSQL("INSERT INTO tblOBSTRUCTION  (Obstruction)  VALUES ('NINGUNA');");
//				 InputStream inputStream = getAssets().open("RF130501.TXT");
			File myFile = new File(o.getPath());
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));

			String line;
			String[] rowData = null;
			while ((line = myReader.readLine()) != null) {
				rowData = line.split(",");
				db1.execSQL("INSERT INTO tblBillboard (Avenue,Date,Starttime,Endtime,Size,Carrier,CarrierDescription,Quality,RealCost,LatandLong,Numberofads,Totaladsinthatlocation,typeofads,Visibilitycode,Visibilitydescription,Verificationdate,Verificationdescription,Versiocode,Versiondescription,Productcode,Constant,CategoryCode,Categorydescription,Subsectorcode,Subsectordescription,Sectorcode,Sectordescription,Betweenavenue,Brandcode,Branddescription,Announcercode,Announcerdescription,Imagecode,Agencycode,Agencyname,Condition,Obstruction) VALUES ("
						+ rowData[0]
						+ ",'"
						+ rowData[1]
						+ "','"
						+ rowData[2]
						+ "','"
						+ rowData[3]
						+ "','"
						+ rowData[4]
						+ "','"
						+ rowData[5]
						+ "','"
						+ rowData[6]
						+ "','"
						+ rowData[7]
						+ "','"
						+ rowData[8]
						+ "','"
						+ rowData[9]
						+ "','"
						+ rowData[10]
						+ "','"
						+ rowData[11]
						+ "','"
						+ rowData[12]
						+ "','"
						+ rowData[13]
						+ "','"
						+ rowData[14]
						+ "','"
						+ rowData[15]
						+ "','"
						+ rowData[16]
						+ "','"
						+ rowData[17]
						+ "','"
						+ rowData[18]
						+ "','"
						+ rowData[19]
						+ "','"
						+ rowData[20]
						+ "','"
						+ rowData[21]
						+ "','"
						+ rowData[22]
						+ "','"
						+ rowData[23]
						+ "','"
						+ rowData[24]
						+ "','"
						+ rowData[25]
						+ "','"
						+ rowData[26]
						+ "','"
						+ rowData[27]
						+ "','"
						+ rowData[28].toString().replace("\\s+", "")
						+ "','"
						+ rowData[29]
						+ "','"
						+ rowData[30]
						+ "','"
						+ rowData[31]
						+ "','"
						+ rowData[32]
						+ "','"
						+ rowData[33] + "','" + rowData[34].toString().replace("\"", "") + "','" + rowData[36].toString().replace("\"", "") + "','" + rowData[37].toString().replace("\"", "") + "');");

			}
			
			// pr.setVisibility(View.INVISIBLE);

			Toast.makeText(getBaseContext(), "File uploaded successfully",
					Toast.LENGTH_SHORT).show();
			// db1.close();

		}

		catch (Exception e) {
			Log.e("HTTP", "Error in http connection " + e.toString());
		}

		/*
		 * finally { if(db1!=null) { db1.close(); } }
		 */
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		if (db1 != null) {
			db1.close();
		}

	}
}